package site.mingdao.boot.job.config;

import com.alibaba.ttl.TtlRunnable;
import jakarta.annotation.Nonnull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Objects;

/**
 * 异步任务 Configuration
 */
@AutoConfiguration
@EnableAsync
public class AsyncAutoConfiguration implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(@Nonnull Object bean, @Nonnull String beanName) throws BeansException {
        // 处理 ThreadPoolTaskExecutor
        if (bean instanceof ThreadPoolTaskExecutor executor) {
            executor.setTaskDecorator(runnable -> TtlRunnable.get(Objects.requireNonNull(runnable)));
            return executor;
        }
        // 处理 SimpleAsyncTaskExecutor
        if (bean instanceof SimpleAsyncTaskExecutor executor) {
            executor.setTaskDecorator(runnable -> TtlRunnable.get(Objects.requireNonNull(runnable)));
            return executor;
        }
        return bean;
    }

}
